import katex from 'katex'

export function getLatexHtmlString (katextEquation) {
  return katex.renderToString(katextEquation, { output: 'mathml', throwOnError: false })
}

export function getLatextSize (fontSize, katextEquation) {
  const katexHtml = katex.renderToString(katextEquation, {
    throwOnError: false,
    errorColor: 'inherit',
    output: 'mathml'
  })
  const katexSpan = document.createElement('span')
  katexSpan.style.fontSize = `${fontSize}px`
  katexSpan.style.position = 'fixed'
  katexSpan.innerHTML = katexHtml
  document.body.append(katexSpan)
  const { width, height } = katexSpan.getBoundingClientRect()
  katexSpan.remove()
  return { width, height }
}

export function validLatex (katextEquation) {
  try {
    katex.renderToString(katextEquation, {
      throwOnError: true,
      output: 'mathml'
    })
    return true
  } catch (error) {
    return false
  }
}
